// SmartInput Chrome扩展统一配置
class SmartInputConfig {
  constructor() {
    // 默认配置
    this.defaults = {
      // API配置
      // apiBase: 'https://192.168.137.122/api',
      // wsBase: 'wss://192.168.137.122/ws',
      apiBase: 'https://api.mensanyun.com/api',
      wsBase: 'wss://api.mensanyun.com/ws',
      
      // 设备配置
      deviceName: 'Chrome Extension',
      deviceType: 'browser_extension',
      
      // 功能开关
      autoConnect: true,
      voiceEnabled: true,
      syncEnabled: true,
      autoInsert: true,
      syncNotification: true,
      showFloatingPanel: false,
      showVoiceButton: true,
      
      // 语音配置
      voiceLanguage: 'zh-CN',
      voiceConfidence: 0.7,
      
      // 同步配置
      syncTarget: 'all',
      
      // 界面配置
      theme: 'light',
      panelPosition: 'top-right',
      
      // 快捷键配置
      voiceShortcut: 'Ctrl+Shift+V',
      syncShortcut: 'Ctrl+Shift+S',
      
      // 调试配置
      debugMode: false,
      logLevel: 'info'
    };
    
    // 当前配置
    this.config = { ...this.defaults };
  }
  
  // 获取配置值
  get(key) {
    return this.config[key] || this.defaults[key];
  }
  
  // 设置配置值
  set(key, value) {
    this.config[key] = value;
  }
  
  // 获取API基础URL
  getApiBase() {
    return this.get('apiBase');
  }
  
  // 获取WebSocket基础URL
  getWsBase() {
    return this.get('wsBase');
  }
  
  // 构建完整的API URL
  buildApiUrl(endpoint) {
    const apiBase = this.getApiBase();
    return `${apiBase}${endpoint.startsWith('/') ? endpoint : `/${endpoint}`}`;
  }
  
  // 构建WebSocket URL
  buildWsUrl(deviceId, token) {
    const wsBase = this.getWsBase();
    const params = new URLSearchParams({
      token: token,
      deviceId: deviceId
    });
    return `${wsBase}/${deviceId}?${params.toString()}`;
  }
  
  // 从存储加载配置
  async loadFromStorage() {
    try {
      const stored = await chrome.storage.local.get(Object.keys(this.defaults));
      
      // 合并存储的配置和默认配置
      this.config = { ...this.defaults, ...stored };
      
      console.log('配置已从存储加载:', this.config);
      return this.config;
    } catch (error) {
      console.error('加载配置失败:', error);
      return this.config;
    }
  }
  
  // 保存配置到存储
  async saveToStorage() {
    try {
      await chrome.storage.local.set(this.config);
      console.log('配置已保存到存储:', this.config);
      return true;
    } catch (error) {
      console.error('保存配置失败:', error);
      return false;
    }
  }
  
  // 重置为默认配置
  async resetToDefaults() {
    this.config = { ...this.defaults };
    await this.saveToStorage();
    console.log('配置已重置为默认值');
  }
  
  // 获取所有配置
  getAll() {
    return { ...this.config };
  }
  
  // 更新配置
  async update(newConfig) {
    this.config = { ...this.config, ...newConfig };
    await this.saveToStorage();
    console.log('配置已更新:', this.config);
  }
  
  // 验证配置
  validate() {
    const errors = [];
    
    // 验证API地址
    try {
      new URL(this.getApiBase());
    } catch (error) {
      errors.push('API地址格式无效');
    }
    
    // 验证WebSocket地址
    try {
      new URL(this.getWsBase());
    } catch (error) {
      errors.push('WebSocket地址格式无效');
    }
    
    // 验证设备名称
    if (!this.get('deviceName') || this.get('deviceName').trim() === '') {
      errors.push('设备名称不能为空');
    }
    
    return {
      valid: errors.length === 0,
      errors: errors
    };
  }
  
  // 获取配置摘要
  getSummary() {
    return {
      apiBase: this.getApiBase(),
      wsBase: this.getWsBase(),
      deviceName: this.get('deviceName'),
      autoConnect: this.get('autoConnect'),
      voiceEnabled: this.get('voiceEnabled'),
      syncEnabled: this.get('syncEnabled'),
      theme: this.get('theme')
    };
  }
}

// 创建全局配置实例
const smartInputConfig = new SmartInputConfig();

// SmartInput Chrome扩展后台脚本
class SmartInputBackground {
  constructor() {
    console.log('SmartInput扩展后台脚本开始初始化');
    this.deviceId = null;
    this.userId = null;
    this.token = null;
    this.websocket = null;
    this.config = smartInputConfig;
    
    // 连接管理相关变量
    this.reconnectTimeout = null;
    this.reconnectAttempts = 0;
    this.maxReconnectAttempts = 5;
    this.heartbeatInterval = null;
    
    // 异步初始化
    this.initializeAsync();
  }

  async initializeAsync() {
    try {
      // 确保deviceId存在
      await this.ensureDeviceId();
      // 初始化
      await this.init();
    } catch (error) {
      console.error('SmartInput扩展初始化失败:', error);
    }
  }

  async ensureDeviceId() {
    const { deviceId } = await chrome.storage.local.get('deviceId');
    console.log('[background][设备ID] 读取到的 deviceId:', deviceId);
    if (!deviceId) {
      const newId = `chrome_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
      await chrome.storage.local.set({ deviceId: newId });
      this.deviceId = newId;
      console.log('[background][设备ID] 兜底生成新 deviceId:', newId);
      return newId;
    }
    this.deviceId = deviceId;
    console.log('[background][设备ID] 最终赋值 deviceId:', this.deviceId);
    return deviceId;
  }

  async init() {
    console.log('SmartInput扩展初始化...');
    // 再次确保deviceId存在
    await this.ensureDeviceId();
    // 加载配置
    await this.loadConfig();
    // 测试连接（带重试机制）
    console.log('测试连接');
    await this.testConnectionWithRetry(3);
    // 设置事件监听器
    this.setupEventListeners();
    
    // 验证存储的登录状态
    if (this.deviceId && this.userId && this.token) {
      console.log('检测到存储的登录信息，保持登录状态');
      // 不进行启动时的token验证，避免网络问题导致登录状态丢失
      // token验证将在WebSocket连接时进行
      console.log('当前状态:', {
        deviceId: this.deviceId,
        userId: this.userId,
        hasToken: !!this.token
      });
      
      // 尝试建立WebSocket连接
      console.log('尝试建立WebSocket连接...');
      await this.initWebSocket();
    } else {
      console.log('用户未登录，跳过WebSocket连接初始化');
      console.log('当前状态:', {
        deviceId: this.deviceId,
        userId: this.userId,
        hasToken: !!this.token
      });
    }
    console.log('SmartInput扩展初始化完成');
  }
async testConnectionWithRetry(maxRetries = 3, retryDelay = 1000) {
    const url = this.config.buildApiUrl('/auth/test');
    console.log(`测试连接URL（尝试 1/${maxRetries}）: ${url}`);
    
    // 检查URL格式
    try {
        new URL(url);
        console.log('URL格式正确');
    } catch (error) {
        console.error('URL格式错误:', error);
        this.notifyPopup({ 
            action: 'connectionStatus', 
            status: 'disconnected', 
            error: 'API地址格式错误'
        });
        return false;
    }
    
    for (let i = 1; i <= maxRetries; i++) {
        try {
            console.log(`开始第 ${i} 次连接测试...`);
            
            const controller = new AbortController();
            const timeoutId = setTimeout(() => {
                console.log('请求超时，中断连接');
                controller.abort();
            }, 10000); // 增加到10秒超时
            
            const fetchOptions = {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json',
                    'User-Agent': 'SmartInput-Chrome-Extension/3.0.0'
                },
                signal: controller.signal,
                mode: 'cors',
                credentials: 'omit'
            };
            
            // 对于自签名证书，尝试不同的请求模式
            if (url.includes('192.168.3.17') || url.includes('localhost')) {
                console.log('检测到本地/开发环境，使用no-cors模式');
                fetchOptions.mode = 'no-cors';
                // 移除可能导致问题的头部
                delete fetchOptions.headers['Content-Type'];
                delete fetchOptions.headers['Accept'];
            }
            
            console.log('发送fetch请求，选项:', fetchOptions);
            
            const response = await fetch(url, fetchOptions);
            clearTimeout(timeoutId);

            console.log('收到响应:', {
                status: response.status,
                statusText: response.statusText,
                url: response.url,
                type: response.type,
                headers: Object.fromEntries(response.headers.entries())
            });

            const data = await response.text();
            console.log('响应体:', data);

            if (response.status >= 200 && response.status < 300) {
                console.log('测试连接成功');
                this.notifyPopup({ action: 'connectionStatus', status: 'connected' });
                return true;
            } else {
                console.error(`测试连接失败（状态码 ${response.status}）`);
                if (i === maxRetries) {
                    this.notifyPopup({ 
                        action: 'connectionStatus', 
                        status: 'disconnected', 
                        error: `服务器返回错误: ${response.status} - ${response.statusText}` 
                    });
                }
                return false;
            }
        } catch (error) {
            console.error(`测试连接失败（尝试 ${i}/${maxRetries}）:`, {
                name: error.name,
                message: error.message,
                stack: error.stack
            });
            
            if (i < maxRetries) {
                console.log(`等待 ${retryDelay}ms 后重试...`);
                await new Promise(resolve => setTimeout(resolve, retryDelay));
            } else {
                console.error('测试连接失败（所有重试均失败）');
                
                let errorMessage = '连接失败';
                if (error.name === 'AbortError' || error.message === 'The user aborted a request.') {
                    errorMessage = '连接超时（10秒）';
                } else if (error.message === 'NetworkError when attempting to fetch resource.' || error.message === 'Failed to fetch') {
                    errorMessage = '网络连接失败，可能的原因：\n1. 后端服务未运行\n2. API地址配置错误\n3. SSL证书不受信任\n4. 防火墙阻止连接\n5. 网络权限不足';
                } else if (error.name === 'TypeError') {
                    errorMessage = '请求类型错误，可能是CORS或权限问题';
                }
                
                this.notifyPopup({ 
                    action: 'connectionStatus', 
                    status: 'disconnected', 
                    error: errorMessage
                });
                return false;
            }
        }
    }
}
  
  async loadConfig() {
    try {
      // 加载统一配置
      await this.config.loadFromStorage();
      
      // 加载用户相关配置
      const result = await chrome.storage.local.get([
        'deviceId',
        'userId',
        'token',
        'userName'
      ]);
      
      this.deviceId = result.deviceId;
      this.userId = result.userId;
      this.token = result.token;
      this.userName = result.userName;
      
      console.log('配置加载完成:', {
        apiBase: this.config.getApiBase(),
        wsBase: this.config.getWsBase(),
        deviceId: this.deviceId,
        userId: this.userId,
        hasToken: !!this.token,
        userName: this.userName
      });
    } catch (error) {
      console.error('加载配置失败:', error);
    }
  }
  
  setupEventListeners() {
    console.log('设置事件监听器');
    
    // 监听来自popup和content script的消息
    chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
      console.log('收到消息:', request);
      this.handleMessage(request, sender, sendResponse);
      return true; // 保持消息通道开放
    });
    
    // 监听扩展安装
    chrome.runtime.onInstalled.addListener((details) => {
      console.log('扩展安装事件触发:', details);
      this.handleInstall(details);
    });
    
    // 监听标签页更新
    chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
      console.log('标签页更新事件触发:', { tabId, changeInfo, tabUrl: tab.url });
      this.handleTabUpdate(tabId, changeInfo, tab);
    });
    
    // 监听快捷键
    chrome.commands.onCommand.addListener((command) => {
      console.log('快捷键事件触发:', command);
      this.handleCommand(command);
    });
    
    console.log('事件监听器设置完成');
  }
  
  async handleMessage(request, sender, sendResponse) {
    console.log('处理消息:', request);
    try {
      switch (request.action) {
        case 'getStatus':
          console.log('获取状态请求');
          const isConnected = this.websocket?.readyState === WebSocket.OPEN;
          const connectionStatus = {
            isConnected: isConnected,
            websocketState: this.websocket?.readyState || 'CLOSED',
            deviceId: this.deviceId,
            userId: this.userId,
            userName: this.userName,
            token: this.token, // 返回实际的token值
            hasToken: !!this.token,
            apiBase: this.config.getApiBase(),
            lastHeartbeat: this.lastHeartbeatTime || null,
            reconnectAttempts: this.reconnectAttempts || 0
          };
          console.log('返回状态信息:', connectionStatus);
          sendResponse(connectionStatus);
          break;
          
        case 'updateConfig':
          console.log('更新配置请求:', request.config);
          await this.updateConfig(request.config);
          sendResponse({ success: true });
          break;
          
        case 'login':
          console.log('登录请求');
          await this.login(request.credentials);
          sendResponse({ 
            success: true, 
            userId: this.userId, 
            token: this.token 
          });
          break;
          
        case 'register':
          console.log('注册请求');
          await this.register(request.credentials);
          sendResponse({ success: true });
          break;
          
        case 'logout':
          console.log('登出请求');
          await this.logout();
          sendResponse({ success: true });
          break;
          
        case 'reconnect':
          console.log('重新连接请求');
          try {
            // 关闭现有连接
            if (this.websocket) {
              this.websocket.close();
              this.websocket = null;
            }
            
            // 重新初始化WebSocket连接
            await this.initWebSocket();
            sendResponse({ success: true });
          } catch (error) {
            console.error('重新连接失败:', error);
            sendResponse({ success: false, error: error.message });
          }
          break;
          
        case 'validateToken':
          console.log('验证token请求');
          const isValid = await this.validateToken();
          sendResponse({ valid: isValid });
          break;
          
        case 'testConnection':
          console.log('测试连接请求');
          const testResult = await this.testConnectionWithRetry(1, 1000);
          sendResponse({ 
            success: testResult,
            message: testResult ? '连接成功' : '连接失败'
          });
          break;
          
        case 'getCurrentTab':
          console.log('获取当前标签页请求');
          const tab = await this.getCurrentTab();
          sendResponse({ tab });
          break;
          
        default:
          console.warn('未知操作:', request.action);
          sendResponse({ error: '未知操作' });
      }
      console.log('消息处理完成:', request.action);
    } catch (error) {
      console.error('处理消息失败:', error);
      sendResponse({ error: error.message });
    }
  }
  
  async handleInstall(details) {
    console.log('处理安装事件:', details);
    if (details.reason === 'install') {
      console.log('SmartInput扩展已安装');
      // 检查是否已有deviceId，避免重复生成
      const { deviceId } = await chrome.storage.local.get('deviceId');
      let finalDeviceId = deviceId;
      if (!deviceId) {
        finalDeviceId = `chrome_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
        await chrome.storage.local.set({ deviceId: finalDeviceId });
      }
      try {
        // 保存初始配置
        await this.config.saveToStorage();
        console.log('初始配置保存完成');
        
        // 注意：不在安装时注册设备，等待用户登录后再注册
        console.log('设备注册将在用户登录后进行');
        
        // 显示欢迎页面
        chrome.tabs.create({
          url: chrome.runtime.getURL('welcome.html')
        });
        console.log('欢迎页面已打开');
      } catch (error) {
        console.error('保存初始配置失败:', error);
        // 即使保存配置失败，也继续显示欢迎页面
        chrome.tabs.create({
          url: chrome.runtime.getURL('welcome.html')
        });
      }
    } else {
      console.log('非安装事件，原因:', details.reason);
    }
  }



  async handleTabUpdate(tabId, changeInfo, tab) {
    console.log('处理标签页更新:', { tabId, changeInfo, tabUrl: tab.url });
    if (changeInfo.status === 'complete' && tab.url) {
      // 向content script发送页面更新通知
      try {
        console.log('向标签页发送页面加载完成消息:', tabId);
        await chrome.tabs.sendMessage(tabId, {
          action: 'pageLoaded',
          url: tab.url,
          title: tab.title
        });
        console.log('页面加载完成消息发送成功:', tabId);
      } catch (error) {
        console.log('Content script可能还没有加载或未在当前页面运行:', tabId);
      }
    }
  }
  
  async handleCommand(command) {
    console.log('处理快捷键命令:', command);
    switch (command) {
      case '_execute_action':
        console.log('执行扩展动作');
        // 打开popup
        break;
      case 'start_voice_recording':
        console.log('开始语音录音命令');
        await this.startVoiceRecording();
        break;
      case 'stop_voice_recording':
        console.log('停止语音录音命令');
        await this.stopVoiceRecording();
        break;
      default:
        console.warn('未知快捷键命令:', command);
    }
    console.log('快捷键命令处理完成:', command);
  }
  
  async registerDevice() {
    console.log('开始设备注册流程');
    
    if (!this.userId || !this.token) {
      console.warn('无法注册设备：缺少用户登录信息');
      return;
    }
    
    if (!this.deviceId) {
      console.warn('无法注册设备：缺少设备ID');
      return;
    }
    
    try {
      console.log('正在注册设备:', { 
        deviceId: this.deviceId,
        userId: this.userId,
        userName: this.userName
      });
      const url = this.config.buildApiUrl('/devices/register');
      
      // 准备请求体
      const requestBody = {
        deviceId: this.deviceId,
        deviceName: 'Chrome Extension',
        deviceType: 'browser_extension',
        userId: this.userId
      };
      
      console.log('设备注册请求体:', requestBody);
      
      // 发送请求
      const response = await fetch(url, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${this.token}`
        },
        body: JSON.stringify(requestBody)
      });
      
      console.log('设备注册响应状态:', response.status);
      
      if (response.ok) {
        const result = await response.json();
        console.log('设备注册成功:', result);
        
        // 通知popup设备注册成功
        this.notifyPopup({ 
          action: 'deviceRegistered', 
          deviceId: this.deviceId 
        });
      } else {
        const errorText = await response.text();
        console.error('设备注册失败:', response.status, errorText);
      }
    } catch (error) {
      console.error('设备注册失败:', error);
    }
  }
  
  async initWebSocket() {
    console.log('初始化WebSocket连接');
    if (!this.deviceId) {
      console.warn('无法初始化WebSocket：缺少设备ID');
      return;
    }
    
    if (!this.token) {
      console.warn('无法初始化WebSocket：缺少用户token');
      return;
    }
    
    // 验证token有效性
    console.log('验证token有效性...');
    const tokenValid = await this.validateToken();
    if (tokenValid === false) {
      console.warn('Token已过期，需要重新登录');
      // 清除无效的token
      this.token = null;
      this.userId = null;
      this.userName = null;
      await chrome.storage.local.remove(['token', 'userId', 'userName']);
      
      // 通知popup需要重新登录
      this.notifyPopup({ 
        action: 'connectionStatus', 
        status: 'token_expired',
        message: 'Token已过期，请重新登录'
      });
      return;
    } else if (tokenValid === null) {
      console.warn('Token验证失败（网络错误），保留登录状态并尝试连接');
      // 网络错误时保留登录状态，不强制登出
    } else {
      console.log('Token验证成功');
    }
    
    try {
      // 使用统一配置构建WebSocket地址
      const wsUrl = this.config.buildWsUrl(this.deviceId, this.token);
      
      console.log('正在创建WebSocket连接:', wsUrl);
      this.websocket = new WebSocket(wsUrl);
      
      this.websocket.onopen = () => {
        console.log('WebSocket连接已建立，状态:', this.websocket.readyState);
        // 通知popup连接状态
        this.notifyPopup({ action: 'connectionStatus', status: 'connected' });
        
        // 立即发送一个连接确认消息
        const connectionData = {
          type: 'connection_confirm',
          deviceId: this.deviceId,
          timestamp: Date.now()
        };
        this.websocket.send(JSON.stringify(connectionData));
        
        // 开始发送心跳（立即发送第一个心跳）
        this.sendHeartbeat();
        
        // 清除重连定时器
        if (this.reconnectTimeout) {
          clearTimeout(this.reconnectTimeout);
          this.reconnectTimeout = null;
        }
      };
      
      this.websocket.onmessage = (event) => {
        console.log('收到WebSocket消息:', event.data);
        this.handleWebSocketMessage(event.data);
      };
      
      this.websocket.onclose = (event) => {
        console.log('WebSocket连接已关闭，代码:', event.code, '原因:', event.reason);
        // 通知popup连接状态
        this.notifyPopup({ action: 'connectionStatus', status: 'disconnected' });
        
        // 根据关闭代码决定重连策略
        if (event.code === 1000 || event.code === 1001) {
          // 正常关闭，3秒后重连
          console.log('正常关闭，3秒后重连');
          setTimeout(() => this.scheduleReconnect(), 3000);
        } else {
          // 异常关闭，立即重连
          console.log('异常关闭，立即重连');
          this.scheduleReconnect();
        }
      };
      
      this.websocket.onerror = (error) => {
        console.error('WebSocket错误:', error);
        // 通知popup连接状态
        this.notifyPopup({ action: 'connectionStatus', status: 'error', error: error.message });
      };
    } catch (error) {
      console.error('初始化WebSocket失败:', error);
      // 通知popup连接状态
      this.notifyPopup({ action: 'connectionStatus', status: 'error', error: error.message });
    }
  }
  
  sendHeartbeat() {
    console.log('发送心跳包');
    if (this.websocket?.readyState === WebSocket.OPEN) {
      const heartbeatData = {
        type: 'heartbeat',
        deviceId: this.deviceId,
        timestamp: Date.now()
      };
      console.log('发送心跳数据:', heartbeatData);
      this.websocket.send(JSON.stringify(heartbeatData));
      
      // 记录心跳时间
      this.lastHeartbeatTime = Date.now();
      
      // 清除之前的心跳定时器
      if (this.heartbeatInterval) {
        clearTimeout(this.heartbeatInterval);
      }
      
      // 每15秒发送一次心跳（更频繁，提高连接稳定性）
      this.heartbeatInterval = setTimeout(() => this.sendHeartbeat(), 15000);
    } else {
      console.warn('WebSocket未连接，无法发送心跳包');
      // 清除心跳定时器
      if (this.heartbeatInterval) {
        clearTimeout(this.heartbeatInterval);
        this.heartbeatInterval = null;
      }
      // 如果WebSocket未连接，尝试重连
      this.scheduleReconnect();
    }
  }
  
  scheduleReconnect() {
    console.log('安排重连...');
    
    // 检查重连次数限制
    if (this.reconnectAttempts >= this.maxReconnectAttempts) {
      console.warn('达到最大重连次数，停止重连');
      this.notifyPopup({ 
        action: 'connectionStatus', 
        status: 'disconnected', 
        error: '连接失败，已达到最大重连次数'
      });
      return;
    }
    
    // 避免重复重连
    if (this.reconnectTimeout) {
      clearTimeout(this.reconnectTimeout);
    }
    
    this.reconnectAttempts++;
    const delay = Math.min(3000 * this.reconnectAttempts, 30000); // 递增延迟，最大30秒
    
    console.log(`第${this.reconnectAttempts}次重连，${delay}ms后执行...`);
    
    this.reconnectTimeout = setTimeout(() => {
      console.log('执行重连...');
      this.initWebSocket().catch(error => {
        console.error('重连失败:', error);
        // 如果重连失败，继续重连
        this.scheduleReconnect();
      });
    }, delay);
  }
  
  handleWebSocketMessage(data) {
    console.log('处理WebSocket消息:', data);
    try {
      const message = JSON.parse(data);
      console.log('解析WebSocket消息:', message);
      
      switch (message.type) {
        case 'connection_established':
          console.log('WebSocket连接已确认建立');
          // 通知popup连接状态
          this.notifyPopup({ action: 'connectionStatus', status: 'connected' });
          break;
        case 'connection_confirm':
          console.log('收到连接确认响应');
          // 连接确认成功，状态良好
          break;
        case 'connection_confirm_response':
          console.log('收到连接确认响应 (connection_confirm_response)');
          // 连接确认成功，状态良好
          break;
        case 'heartbeat_response':
          console.log('收到心跳响应:', message.data?.timestamp);
          // 心跳响应正常，连接状态良好
          // 重置重连计数器
          this.reconnectAttempts = 0;
          break;
        case 'text_input':
          console.log('处理手机端文字输入消息');
          this.handleMobileTextInput(message);
          break;
        case 'voice_recognition_result':
          console.log('处理语音识别结果消息');
          this.handleVoiceRecognitionResult(message);
          break;
        case 'notification':
          console.log('处理通知消息');
          this.showNotification(message);
          break;
        default:
          console.warn('未知WebSocket消息类型:', message.type);
      }
    } catch (error) {
      console.error('处理WebSocket消息失败:', error);
    }
  }
  
  async startVoiceRecording() {
    // 移除录音功能
    console.log('录音功能已移除');
    return;
  }
  
  async stopVoiceRecording() {
    // 移除录音功能
    console.log('录音功能已移除');
    return;
  }
  
  async processAudioData() {
    // 移除音频处理功能
    console.log('音频处理功能已移除');
    return;
  }
  
  async syncText(text, target = 'current') {
    // 移除文字同步功能
    console.log('文字同步功能已移除');
    return;
  }
  
  async login(credentials) {
    try {
      const loginUrl = this.config.buildApiUrl('/auth/login');
      console.log('尝试登录到:', loginUrl);
      const response = await fetch(this.config.buildApiUrl('/auth/login'), {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(credentials)
      });
      
      if (!response.ok) {
        let errorMessage = `登录失败: ${response.status} ${response.statusText}`;
        try {
          const errorData = await response.json();
          errorMessage = errorData.message || errorMessage;
        } catch (e) {
          // 处理非JSON响应
          console.log('非JSON错误响应:', await response.text());
        }
        throw new Error(errorMessage);
      }
      
      const result = await response.json();
      console.log('登录API返回结果:', result);
      
      if (!result.success) {
        throw new Error(result.status?.message || '登录失败');
      }
      
      // 从 data 字段中提取用户信息
      const userData = result.data;
      if (!userData) {
        throw new Error('登录响应缺少用户数据');
      }
      
      this.token = userData.token;
      this.userId = userData.userId;
      this.userName = userData.userName;
      
      await chrome.storage.local.set({
        token: this.token,
        userId: this.userId,
        userName: this.userName
      });
      
      console.log('登录成功，用户信息:', {
        userId: this.userId,
        userName: this.userName,
        token: this.token ? `${this.token.substring(0, 20)}...` : 'null'
      });

      // 登录成功后自动注册设备
      if (this.deviceId) {
        console.log('登录成功，开始注册设备...');
        await this.registerDevice();
      } else {
        console.warn('登录成功，但无法注册设备：缺少设备ID');
      }

      // 登录成功后建立WebSocket连接
      if (this.deviceId) {
        console.log('登录成功，建立WebSocket连接...');
        await this.initWebSocket();
      } else {
        console.warn('登录成功，但无法建立WebSocket连接：缺少设备ID');
      }
    } catch (error) {
      console.error('登录失败:', error);
      throw error;
    }
  }
  
  async register(credentials) {
    try {
      const registerUrl = this.config.buildApiUrl('/auth/register');
      console.log('尝试注册到:', registerUrl);
      const response = await fetch(this.config.buildApiUrl('/auth/register'), {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(credentials)
      });
      
      let result = {};
      try {
        result = await response.json(); // 只读取一次
      } catch (e) {
        // 不是JSON，兜底
        result = {};
      }

      if (!response.ok) {
        let errorMessage = `注册失败: ${response.status} ${response.statusText}`;
        errorMessage = result.message || errorMessage;
        throw new Error(errorMessage);
      }
      if (!result.success) {
        throw new Error(result.status?.message || '注册失败');
      }
      
      console.log('注册成功');
    } catch (error) {
      console.error('注册失败:', error);
      throw error;
    }
  }
  
  async logout() {
    // 关闭WebSocket连接
    if (this.websocket) {
      console.log('登出时关闭WebSocket连接');
      this.websocket.close();
      this.websocket = null;
    }
    
    this.token = null;
    this.userId = null;
    this.userName = null;
    
    await chrome.storage.local.remove(['token', 'userId', 'userName']);
    
    console.log('已登出');
  }

  async validateToken() {
    try {
      console.log('验证token有效性');
      const response = await fetch(this.config.buildApiUrl('/auth/validate'), {
        method: 'GET',
        headers: {
          'Authorization': `Bearer ${this.token}`,
          'Content-Type': 'application/json'
        }
      });
      
      if (response.ok) {
        console.log('token验证成功');
        return true;
      } else if (response.status === 401) {
        console.log('token已过期，清除登录信息');
        // 只有明确返回401时才清除登录信息
        this.token = null;
        this.userId = null;
        this.userName = null;
        await chrome.storage.local.remove(['token', 'userId', 'userName']);
        return false;
      } else {
        console.log('token验证失败，但保留登录状态（状态码: ${response.status}）');
        // 其他错误状态码不清除登录信息，可能是服务器问题
        return null;
      }
    } catch (error) {
      console.error('token验证失败（网络错误）:', error);
      // 网络错误时保留token，可能是临时网络问题
      return null; // 返回null表示网络错误，不明确是token无效
    }
  }
  
  async updateConfig(config) {
    await chrome.storage.local.set(config);
    
    // 更新本地配置
    Object.assign(this, config);
    
    console.log('配置已更新');
  }
  
  async getCurrentTab() {
    const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
    return tab;
  }
  
  async sendToCurrentTab(message) {
    try {
      const tab = await this.getCurrentTab();
      
      // 检查标签页是否存在且可访问
      if (!tab || !tab.id) {
        console.log('没有找到活动标签页');
        return;
      }
      
      console.log('当前标签页信息:', { id: tab.id, url: tab.url, title: tab.title });
      
      // 检查标签页URL是否支持内容脚本
      if (tab.url && (tab.url.startsWith('chrome://') || tab.url.startsWith('chrome-extension://') || tab.url.startsWith('about:') || tab.url.startsWith('edge://') || tab.url.startsWith('moz-extension://'))) {
        console.log('当前标签页不支持内容脚本:', tab.url);
        console.log('提示：请在普通网页（如 https://www.google.com）上测试此功能');
        return;
      }
      
      console.log('尝试发送消息到标签页:', tab.id);
      const response = await chrome.tabs.sendMessage(tab.id, message);
      console.log('消息发送成功，响应:', response);
      
      // 处理插入结果
      if (response && response.inserted) {
        console.log('文字插入成功，目标类型:', response.targetType);
        return { success: true, inserted: true, targetType: response.targetType };
      } else {
        console.log('文字插入失败或未找到目标元素');
        return { success: true, inserted: false };
      }
    } catch (error) {
      // 忽略连接错误，这是正常的（当标签页没有内容脚本时）
      if (error.message.includes('Receiving end does not exist')) {
        console.log('当前标签页没有加载内容脚本，尝试动态注入...');
        
        // 尝试动态注入内容脚本
        try {
          const currentTab = await this.getCurrentTab();
          if (currentTab && currentTab.id) {
            await this.injectContentScript(currentTab.id);
            console.log('内容脚本注入成功，等待初始化...');
            
            // 等待更长时间让脚本完全初始化
            setTimeout(async () => {
              try {
                console.log('尝试发送消息到标签页:', currentTab.id);
                
                // 先检查内容脚本是否已准备好
                const checkResult = await chrome.scripting.executeScript({
                  target: { tabId: currentTab.id },
                  func: () => {
                    return {
                      initialized: window.smartInputInitialized,
                      chromeRuntime: typeof chrome.runtime,
                      ready: true
                    };
                  }
                });
                
                if (checkResult && checkResult[0] && checkResult[0].result) {
                  console.log('内容脚本状态检查:', checkResult[0].result);
                }
                
                const retryResponse = await chrome.tabs.sendMessage(currentTab.id, message);
                console.log('消息发送成功（动态注入后），响应:', retryResponse);
                
                // 处理插入结果
                if (retryResponse && retryResponse.inserted) {
                  console.log('文字插入成功，目标类型:', retryResponse.targetType);
                  return { success: true, inserted: true, targetType: retryResponse.targetType };
                } else {
                  console.log('文字插入失败或未找到目标元素');
                  return { success: true, inserted: false };
                }
              } catch (retryError) {
                console.log('重试发送消息失败，尝试再次注入:', retryError);
                
                // 检查标签页是否仍然存在
                try {
                  const tab = await chrome.tabs.get(currentTab.id);
                  if (!tab) {
                    console.log('标签页已关闭，无法发送消息');
                    return { success: false, inserted: false, error: '标签页已关闭' };
                  }
                } catch (tabError) {
                  console.log('无法获取标签页信息，可能已关闭:', tabError);
                  return { success: false, inserted: false, error: '无法获取标签页信息' };
                }
                
                // 如果还是失败，尝试再次注入并等待
                try {
                  await this.injectContentScript(currentTab.id);
                  console.log('第二次注入完成，再次尝试发送消息');
                  
                  setTimeout(async () => {
                    try {
                      console.log('最终尝试发送消息到标签页:', currentTab.id);
                      const finalResponse = await chrome.tabs.sendMessage(currentTab.id, message);
                      console.log('消息发送成功（第二次注入后），响应:', finalResponse);
                      
                      // 处理插入结果
                      if (finalResponse && finalResponse.inserted) {
                        console.log('文字插入成功，目标类型:', finalResponse.targetType);
                        return { success: true, inserted: true, targetType: finalResponse.targetType };
                      } else {
                        console.log('文字插入失败或未找到目标元素');
                        return { success: true, inserted: false };
                      }
                    } catch (finalError) {
                      console.log('最终发送失败:', finalError);
                      console.log('可能的原因：内容脚本未正确初始化或标签页不支持');
                      return { success: false, inserted: false, error: finalError.message };
                    }
                  }, 1500);
                } catch (secondInjectError) {
                  console.log('第二次注入也失败:', secondInjectError);
                  return { success: false, inserted: false, error: secondInjectError.message };
                }
              }
            }, 1500);
          } else {
            console.log('无法获取当前标签页信息');
          }
        } catch (injectError) {
          console.log('动态注入内容脚本失败:', injectError);
          
          // 提供更详细的错误信息
          if (injectError.message.includes('extensions gallery cannot be scripted')) {
            console.log('错误原因：当前页面是扩展程序页面，不允许注入脚本');
            console.log('解决方案：请在普通网页（如 https://www.google.com）上测试此功能');
            return { success: false, inserted: false, error: '当前页面不支持脚本注入' };
          } else if (injectError.message.includes('Cannot access a chrome:// URL')) {
            console.log('错误原因：当前页面是Chrome内部页面，不允许注入脚本');
            console.log('解决方案：请在普通网页上测试此功能');
            return { success: false, inserted: false, error: 'Chrome内部页面不支持脚本注入' };
          } else {
            console.log('提示：请确保在普通网页（如 https://www.google.com）上测试');
            return { success: false, inserted: false, error: injectError.message };
          }
        }
      } else {
        console.error('发送消息到标签页失败:', error);
      }
    }
  }
  
  async injectContentScript(tabId) {
    try {
      console.log('开始动态注入内容脚本到标签页:', tabId);
      
      // 先检查是否已经注入过
      const checkResult = await chrome.scripting.executeScript({
        target: { tabId: tabId },
        func: () => {
          return {
            configLoaded: typeof SmartInputConfig !== 'undefined',
            contentLoaded: typeof SmartInputContent !== 'undefined',
            initialized: window.smartInputInitialized
          };
        }
      });
      
      if (checkResult && checkResult[0] && checkResult[0].result) {
        const status = checkResult[0].result;
        console.log('当前注入状态:', status);
        
        // 如果已经初始化，不需要重新注入
        if (status.initialized) {
          console.log('内容脚本已经初始化，跳过注入');
          return;
        }
      }
      
      // 注入配置脚本（如果还没有加载）
      if (!checkResult || !checkResult[0] || !checkResult[0].result.configLoaded) {
        await chrome.scripting.executeScript({
          target: { tabId: tabId },
          files: ['config.js']
        });
        console.log('配置脚本注入完成');
      } else {
        console.log('配置脚本已存在，跳过注入');
      }
      
      // 注入内容脚本（如果还没有加载）
      if (!checkResult || !checkResult[0] || !checkResult[0].result.contentLoaded) {
        await chrome.scripting.executeScript({
          target: { tabId: tabId },
          files: ['content.js']
        });
        console.log('内容脚本注入完成');
      } else {
        console.log('内容脚本已存在，跳过注入');
      }
      
      // 注入样式
      await chrome.scripting.insertCSS({
        target: { tabId: tabId },
        files: ['content.css']
      });
      console.log('样式注入完成');
      
      // 手动触发内容脚本初始化
      await chrome.scripting.executeScript({
        target: { tabId: tabId },
        func: () => {
          console.log('开始手动初始化SmartInput内容脚本');
          
          // 检查是否已经初始化
          if (window.smartInputInitialized) {
            console.log('SmartInput已经初始化过');
            return;
          }
          
          // 手动创建SmartInputContent实例
          if (typeof SmartInputContent !== 'undefined') {
            console.log('找到SmartInputContent类，开始初始化');
            try {
              new SmartInputContent();
              console.log('SmartInputContent实例创建成功');
            } catch (error) {
              console.error('SmartInputContent实例创建失败:', error);
            }
          } else {
            console.log('SmartInputContent类未定义，等待自动初始化');
            // 等待一段时间后再次检查
            setTimeout(() => {
              if (typeof SmartInputContent !== 'undefined' && !window.smartInputInitialized) {
                console.log('延迟初始化SmartInputContent');
                try {
                  new SmartInputContent();
                } catch (error) {
                  console.error('延迟初始化失败:', error);
                }
              }
            }, 1000);
          }
        }
      });
      
      // 再次检查初始化状态
      await chrome.scripting.executeScript({
        target: { tabId: tabId },
        func: () => {
          console.log('检查初始化状态:');
          console.log('- window.smartInputInitialized:', window.smartInputInitialized);
          console.log('- typeof SmartInputContent:', typeof SmartInputContent);
          console.log('- chrome.runtime:', typeof chrome.runtime);
          return {
            initialized: window.smartInputInitialized,
            smartInputContent: typeof SmartInputContent,
            chromeRuntime: typeof chrome.runtime
          };
        }
      }).then((results) => {
        if (results && results[0]) {
          console.log('初始化状态检查结果:', results[0].result);
        }
      }).catch((error) => {
        console.log('检查初始化状态失败:', error);
      });
      
      console.log('动态注入完成');
      
      // 等待内容脚本初始化
      return new Promise((resolve) => {
        let resolved = false;
        
        const timeout = setTimeout(() => {
          if (!resolved) {
            console.log('等待内容脚本初始化超时，继续执行');
            resolved = true;
            resolve();
          }
        }, 3000);
        
        // 监听内容脚本初始化完成消息
        const messageListener = (message, sender) => {
          console.log('收到消息:', message.action, '来自标签页:', sender.tab?.id);
          
          if (sender.tab?.id === tabId && message.action === 'contentScriptReady') {
            console.log('收到内容脚本初始化完成消息');
            if (!resolved) {
              clearTimeout(timeout);
              chrome.runtime.onMessage.removeListener(messageListener);
              resolved = true;
              resolve();
            }
          }
        };
        
        chrome.runtime.onMessage.addListener(messageListener);
        
        // 定期检查初始化状态
        const checkInterval = setInterval(() => {
          if (!resolved) {
            chrome.scripting.executeScript({
              target: { tabId: tabId },
              func: () => {
                console.log('检查初始化状态:', window.smartInputInitialized);
                return window.smartInputInitialized;
              }
            }).then((results) => {
              if (results && results[0] && results[0].result === true) {
                console.log('检测到内容脚本已初始化');
                if (!resolved) {
                  clearTimeout(timeout);
                  clearInterval(checkInterval);
                  chrome.runtime.onMessage.removeListener(messageListener);
                  resolved = true;
                  resolve();
                }
              }
            }).catch((error) => {
              console.log('检查初始化状态失败:', error);
            });
          }
        }, 500);
      });
    } catch (error) {
      console.error('动态注入失败:', error);
      throw error;
    }
  }
  
  notifyPopup(message) {
    chrome.runtime.sendMessage(message).catch(() => {
      // popup可能没有打开
    });
  }
  
  showNotification(notification) {
    const notificationId = 'smartinput_' + Date.now();
    
    try {
      // 确保通知有必要的属性
      const notificationData = {
        type: 'basic',
        title: notification.title || 'SmartInput',
        message: notification.message || '收到新消息'
      };
      
      // 尝试添加图标（如果存在）
      try {
        const iconUrl = chrome.runtime.getURL('icons/icon48.png');
        notificationData.iconUrl = iconUrl;
      } catch (iconError) {
        console.log('图标加载失败，使用默认通知:', iconError);
      }
      
      // 尝试创建通知
      chrome.notifications.create(notificationId, notificationData, (createdId) => {
        if (chrome.runtime.lastError) {
          console.log('通知创建失败:', chrome.runtime.lastError.message);
          // 尝试创建最简单的通知
          try {
            chrome.notifications.create(notificationId + '_simple', {
              type: 'basic',
              title: notification.title || 'SmartInput',
              message: notification.message || '收到新消息'
            }, (simpleId) => {
              if (chrome.runtime.lastError) {
                console.log('简单通知也创建失败:', chrome.runtime.lastError.message);
              } else {
                console.log('简单通知创建成功:', simpleId);
              }
            });
          } catch (simpleError) {
            console.log('简单通知创建异常:', simpleError);
          }
        } else {
          console.log('通知创建成功:', createdId);
        }
      });
    } catch (error) {
      console.log('通知创建异常（忽略）:', error);
    }
  }
  
  showPageNotification(title, message) {
    // 通过content script在页面上显示通知
    this.sendToCurrentTab({
      action: 'showPageNotification',
      title: title,
      message: message
    }).catch(error => {
      console.log('页面通知发送失败:', error);
    });
  }
  
  async handleMobileTextInput(message) {
    console.log('处理手机端文字输入:', message);
    
    // 从data字段获取文本信息
    const text = message.data?.text || message.text || '';
    const source = message.data?.source || message.source || 'mobile';
    const timestamp = message.data?.timestamp || message.timestamp || Date.now();
    
    console.log('解析后的文本信息:', { text, source, timestamp });
    
    // 发送文字到当前标签页
    const insertResult = await this.sendToCurrentTab({
      action: 'mobileTextInput',
      text: text,
      source: source,
      timestamp: timestamp
    });
    
    console.log('插入结果:', insertResult);
    
    // 根据插入结果显示不同的通知
    if (insertResult && insertResult.inserted) {
      console.log('文字插入成功，目标类型:', insertResult.targetType);
      // 去掉文字插入成功的通知提示
      // this.showPageNotification('文字插入成功', `文字已插入到${insertResult.targetType === 'INPUT' ? '输入框' : '页面'}`);
    } else {
      console.log('文字插入失败或未找到目标元素');
      // 去掉文字插入失败的通知提示
      // this.showPageNotification('文字插入失败', '未找到合适的输入框，请点击输入框后重试');
    }
    
    // 通知popup更新状态
    this.notifyPopup({
      action: 'mobileTextReceived',
      text: text,
      source: source,
      inserted: insertResult ? insertResult.inserted : false
    });
  }
  
  async handleVoiceRecognitionResult(message) {
    console.log('处理语音识别结果:', message);
    
    // 从data字段获取识别结果信息
    const text = message.data?.text || message.text || '';
    const isFinal = message.data?.isFinal !== undefined ? message.data.isFinal : true;
    const timestamp = message.data?.timestamp || message.timestamp || Date.now();
    
    console.log('解析后的识别结果:', { text, isFinal, timestamp });
    
    if (isFinal) {
      // 最终结果：直接插入文本
      console.log('处理最终识别结果，插入文本:', text);
      
      const insertResult = await this.sendToCurrentTab({
        action: 'mobileTextInput',
        text: text,
        source: 'voice_recognition_final',
        timestamp: timestamp
      });
      
      console.log('最终结果插入结果:', insertResult);
      
      // 根据插入结果显示通知
      if (insertResult && insertResult.inserted) {
        // 去掉语音识别完成后的文字插入通知提示
        // this.showPageNotification('语音识别完成', `文字已插入: ${text.substring(0, 20)}...`);
      } else {
        // 去掉语音识别完成但插入失败的通知提示
        // this.showPageNotification('语音识别完成但插入失败', '请点击输入框后重试');
      }
      
      // 通知popup更新状态
      this.notifyPopup({
        action: 'voiceRecognitionResult',
        text: text,
        isFinal: true,
        inserted: insertResult ? insertResult.inserted : false
      });
    } else {
      // 临时结果：仅显示预览，不插入
      console.log('处理临时识别结果，显示预览:', text);
      
      // 发送临时结果到页面进行预览显示
      await this.sendToCurrentTab({
        action: 'voiceRecognitionPreview',
        text: text,
        source: 'voice_recognition_interim',
        timestamp: timestamp
      });
      
      // 通知popup更新状态
      this.notifyPopup({
        action: 'voiceRecognitionResult',
        text: text,
        isFinal: false,
        inserted: false
      });
    }
  }
}

// 初始化后台脚本
new SmartInputBackground();